import axios from 'axios'
import { Toast } from 'vant'
import useStore from '@/store'
import router from '@/router'
const { user } = useStore()
const instance = axios.create({
  // baseURL: process.env.VUE_APP_BASE_API + process.env.VUE_APP_URL,
  baseURL: process.env.VUE_APP_URL,
  // baseURL: 'http://119.91.150.211:1111/api/v2'
  withCredentials: true
})
instance.interceptors.request.use(
  (config) => {
    config.headers.Authorization = `Bearer ${user.token}`
    return config
  },
  (err) => {
    return Promise.reject(err)
  }
)
instance.interceptors.response.use(
  (res) => {
    if (!res.config.noError && res.data.result && res.data.result.errno !== 0) {
      Toast.fail(res.data.result.reason)
      return Promise.reject(new Error(res.data.result.reason))
    } else {
      return res.data
    }
  },
  (err) => {
    if (err.response && err.response.status === 401) {
      user.setToken('')
      router.push('/login')
    }
    return Promise.reject(err)
  }
)
export default instance
